<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :visible="visible"
    :width="$store.getters.isMobile ? 350 : 600"
    :body-style="{ paddingBottom: '80px' }"
    @close="onCancel"
  >
    <a-form layout="vertical">
      <a-form-item label="备注内容" v-bind="validateInfos.remark">
        <a-textarea
          placeholder="请输入备注内容"
          :auto-size="{ minRows: 6 }"
          v-model:value="modelRef.remark"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onCancel">关闭</a-button>
        <a-button type="primary" @click.prevent="onSubmit"> 保存 </a-button>
      </a-space>
    </div>
  </a-drawer>
</template>

<script>
import { defineComponent, reactive, toRefs, watch } from "vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import { Form, message } from "ant-design-vue";
const useForm = Form.useForm;

export default defineComponent({
  name: "AddRemark",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    content: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props, context) {
    const state = reactive({
      title: "",
    });
    const modelRef = reactive({
      remark: "",
    });
    const ruleRef = reactive({
      remark: [{ required: true, message: "必填" }],
    });

    const { resetFields, validate, validateInfos } = useForm(modelRef, ruleRef);

    const onCancel = () => {
      context.emit("cancel");
    };

    const onSubmit = () => {
      validate().then(() => {
        const { content } = props;
        let requestMethods = "post";
        let requestUrl = "/bill/remark";
        const params = {
          bill_id: store.getters.billMatchAccountDetail.bill_id,
          ...modelRef,
          needMsg: true,
        };
        if (content && content.id) {
          requestMethods = "put";
          requestUrl = "/bill/editRemark";
          params.remark_id = content.id;
        }
        request[requestMethods]("/org", requestUrl, params).then((res) => {
          message.success(res.msg || "保存成功！");
          context.emit("success");
        });
      });
    };

    const init = () => {
      const { content } = props;
      if (content && content.remark) {
        modelRef.remark = content.remark;
        state.title = "编辑备注";
      } else {
        state.title = "添加备注";
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
        }
      }
    );

    return {
      ...toRefs(state),
      modelRef,
      validateInfos,
      onCancel,
      onSubmit,
    };
  },
});
</script>
